const EmailServices = require('../services/emailServices.js')

class EmailControllers {
  constructor() {
    this.sendEmail = this.sendEmail.bind(this)
  }

  // 统一响应函数
  handleRequest = async (serviceMethod, req, res, successStatus = 200) => {
    try {
      const result = await serviceMethod(req);
      if (result.code === 0) {
        res.status(successStatus).json(result); // 成功
      } else {
        res.status(result.statusCode || 400).json(result); // 失败
      }
    } catch (error) {
      console.log(error);
      res.status(500).json({
        code: 1,
        msg: "服务器内部错误",
      });
    }
  };

  async sendEmail(req, res)
  {
    const { to, context } = req.body
    await this.handleRequest(
      () => EmailServices.sendEmail(to, context),
      req,
      res
    )
  }
}

module.exports = new EmailControllers